package com.easylinkin.linkappapi.jkmonior.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.mapper.DeviceMapper;
import com.easylinkin.linkappapi.jkmonior.entity.JkMonitorConfig;
import com.easylinkin.linkappapi.jkmonior.entity.vo.JkMonitorConfigVo;
import com.easylinkin.linkappapi.jkmonior.mapper.JkMonitorConfigMapper;
import com.easylinkin.linkappapi.jkmonior.service.JkMonitorConfigService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.webcammanage.entity.DeviceAttributeStatus;
import com.easylinkin.linkappapi.webcammanage.mapper.DeviceAreaHandlerMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * JkMonitorConfig表服务实现类
 *
 * @author zhengwen
 * @date 2022/10/28
 */
@Slf4j
@Service("appJkMonitorConfigService")
public class JkMonitorConfigServiceImpl extends ServiceImpl
        <JkMonitorConfigMapper, JkMonitorConfig> implements JkMonitorConfigService {
    @Resource
    private CommonService commonService;
    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private DeviceAreaHandlerMapper deviceAreaHandlerMapper;

    @Override
    public boolean saveOne(JkMonitorConfig appJkMonitorConfig) {
        commonService.setCreateAndModifyInfo(appJkMonitorConfig);
        // appJkMonitorConfig.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validParamRequired(appJkMonitorConfig);
        validRepeat(appJkMonitorConfig);
        validParamFormat(appJkMonitorConfig);
        return save(appJkMonitorConfig);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOne(JkMonitorConfig appJkMonitorConfig) {
        Assert.notNull(appJkMonitorConfig.getId(), "id不能为空");
        commonService.setModifyInfo(appJkMonitorConfig);
        //appJkMonitorConfig.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validRepeat(appJkMonitorConfig);
        validParamFormat(appJkMonitorConfig);
        return updateById(appJkMonitorConfig);
    }

    @Override
    public IPage<JkMonitorConfig> selectPage(Page page, JkMonitorConfig appJkMonitorConfig) {
        //appJkMonitorConfig.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page, appJkMonitorConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> idList) {
        return removeByIds(idList);
    }

    @Override
    public void export(JkMonitorConfig appJkMonitorConfig, HttpServletRequest request, HttpServletResponse
            response) {

        IPage<JkMonitorConfig> page = selectPage(new Page(0, -1), appJkMonitorConfig);
        List<JkMonitorConfig> records = page.getRecords();
        List
                <JkMonitorConfigVo> appJkMonitorConfigVos = new ArrayList<>();
        for (JkMonitorConfig expert : records) {
            appJkMonitorConfigVos.add(new JkMonitorConfigVo(expert));
        }

        String keyValue = "名称:name,租户id:tenantId";
        String title = "JkMonitorConfig导出数据";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, appJkMonitorConfigVos, ExcelConstant.XLS, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    @Override
    public RestMessage getJkMonitorBaseConfig() {
        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        String tenantId = linkappUser.getTenantId();

        JkMonitorConfigVo monitorConfigVo = new JkMonitorConfigVo();

        QueryWrapper<JkMonitorConfig> qw = new QueryWrapper();
        qw.eq("tenant_id", tenantId);
        qw.eq("delete_state", 1);
        qw.orderByDesc("create_time");
        List<JkMonitorConfig> list = baseMapper.selectList(qw);
        if (CollectionUtil.isNotEmpty(list)) {
            BeanUtil.copyProperties(list.get(0), monitorConfigVo);
            //查询现场视频设备信息
            String deviceId = monitorConfigVo.getSiteVideoDeviceId();
            if (StringUtils.isNotBlank(deviceId)) {
                Device device = deviceMapper.selectById(deviceId);
                monitorConfigVo.setSiteVideoDevice(device);
            }
        }

        return RestBuilders.successBuilder(monitorConfigVo).build();
    }

    @Override
    public IPage<DeviceAttributeStatus> getVideoList(Page page, Device device) {
        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        String tenantId = linkappUser.getTenantId();
        device.setTenantId(tenantId);
        List<DeviceAttributeStatus> list = deviceAreaHandlerMapper.getVideoTypeDeviceListGlobal(page, device);
        if (CollectionUtil.isEmpty(list)) {
            page.setTotal(0);
            page.setRecords(null);
            return page;
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public RestMessage saveBaseConfig(JkMonitorConfigVo jkMonitorConfigVo) {
        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        String tenantId = linkappUser.getTenantId();
        jkMonitorConfigVo.setTenantId(tenantId);

        //再次查询
        QueryWrapper<JkMonitorConfig> qw = new QueryWrapper();
        qw.eq("tenant_id", tenantId);
        qw.eq("delete_state", 1);
        List<JkMonitorConfig> list = baseMapper.selectList(qw);
        if (CollectionUtil.isNotEmpty(list)) {
            //全部更新
            list.stream().forEach(c -> {
                Integer id = c.getId();
                jkMonitorConfigVo.setId(null);
                BeanUtil.copyProperties(jkMonitorConfigVo, c, CopyOptions.create().setIgnoreNullValue(false));
                c.setId(id);
                c.setModifier(linkappUser.getId().toString());
                c.setModifyTime(DateUtil.date());
                baseMapper.updateById(c);
            });
        } else {
            //为空保存
            JkMonitorConfig jkMonitorConfig = new JkMonitorConfig();
            BeanUtil.copyProperties(jkMonitorConfigVo, jkMonitorConfig, CopyOptions.create().setIgnoreNullValue(true));
            jkMonitorConfig.setCreator(linkappUser.getId().toString());
            jkMonitorConfig.setCreateTime(DateUtil.date());
            jkMonitorConfig.setModifier(jkMonitorConfig.getCreator());
            jkMonitorConfig.setModifyTime(jkMonitorConfig.getCreateTime());
            jkMonitorConfig.setDeleteState(1);
            baseMapper.insert(jkMonitorConfig);
        }

        return RestBuilders.successBuilder().build();
    }

    @Override
    public JkMonitorConfig getOneById(Serializable id) {
        return baseMapper.getOneById(id);
    }

    /**
     * 校验重复
     */
    private void validRepeat(JkMonitorConfig appJkMonitorConfig) {
        /* QueryWrapper<JkMonitorConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", appJkMonitorConfig.getName());
        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<JkMonitorConfig> list = baseMapper.selectList(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            throw new BusinessException("名称有重复");
        }
        if (ObjectUtils.isEmpty(appJkMonitorConfig.getId())) {
            throw new BusinessException("名称已存在");
        }
        if (!appJkMonitorConfig.getId().equals(list.get(0).getId())) {
            throw new BusinessException("名称已存在");
        }
                    */

    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(JkMonitorConfig appJkMonitorConfig) {
        //Assert.notNull(appJkMonitorConfig, "参数为空");
        //Assert.isTrue(StringUtils.isNotBlank(appJkMonitorConfig.getName()), "名称为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(JkMonitorConfig appJkMonitorConfig) {
        //Assert.isTrue(appJkMonitorConfig.getName() == null || appJkMonitorConfig.getName().length() <= 50,
        //        "名称超长");
    }
}

